const path = require('path');
const { createServer } = require('vite');
const styleImport = require('vite-plugin-style-import');
const reactRefresh = require('@vitejs/plugin-react-refresh');

const envConfig = require('./proxy.config');

const devDomain = envConfig.getDomain();

const PORT = process.env.PORT || 10000;
const PROXY = process.env.ip || process.env.IP;

const cookies = {
  current: null,
};

// 代理配置
const configure = (proxy, opts) => {
  proxy.on('proxyReq', (proxyReq, req, res) => {
    proxyReq._headers.cookie = proxyReq._headers.cookie || cookies.current;
    console.log('\nproxyReq headers', proxyReq._headers.cookie);
  });

  proxy.on('proxyRes', (proxyRes, req, res) => {
    // console.log('\nstatusCode', proxyRes.statusCode);
    // console.log('\nstatusMessage', proxyRes.statusMessage);
    // console.log('\nheaders', proxyRes.headers);

    proxyRes.headers['access-control-allow-origin'] = req.headers['origin'];

    if (proxyRes.headers['set-cookie'] !== undefined) {
      console.log('** SET-COOKIE: ', proxyRes.headers['set-cookie']);
      cookies.current = proxyRes.headers['set-cookie']
        .map((d) => d.replace(/Path=.+$/, ''))
        .join(';');
      console.log('cookies.current', cookies.current);
      proxyRes.headers['set-cookie'] = proxyRes.headers['set-cookie'].map((d) =>
        d.replace(/Domain=\w+\.\w+;/, ``)
      );
    }
  });

  proxy.on('error', (err, req, res) => {
    console.log('err', err);
  });
};

const config = {
  plugins: [
    reactRefresh(),
    styleImport.default({
      libs: [
        {
          libraryName: 'antd-mobile',
          esModule: true,
          resolveStyle: (name) => {
            return `antd-mobile/es/${name}/style/index`;
          },
        },
        {
          libraryName: 'antd',
          esModule: true,
          resolveStyle: (name) => {
            return `antd/es/${name}/style/index`;
          },
        },
      ],
    }),
  ],
  /**
   * 在生产中服务时的基本公共路径。
   * @default '/'
   */
  base: '/',
  /**
   * 与“根”相关的目录，构建输出将放在其中。如果目录存在，它将在构建之前被删除。
   * @default 'dist'
   */
  outDir: 'dist',
  emitManifest: true,
  // 引入第三方的配置
  optimizeDeps: {
    // include: [],
    // exclude: [],
  },
  resolve: {
    alias: {
      // vite中alias必须以斜线开头和结尾，暂时未知原因，这样其实挺不方便的
      // 所以在eslint配置alias和文件中导入路径也要相应的修改
      '~': path.resolve(__dirname, './client'),
      '/@': path.resolve(__dirname, './src'),
      // 'vue': path.resolve(__dirname, './node_modules/vue/dist/vue.runtime.esm-browser.js'),
    },
  },
  //这里注意，键名是scss不是sass！一字之差能让你折腾好久
  // scss: {
  //   //这里写你想导入全局scss变量的路径
  //   //这里注意只能写相对路径，alias貌似在css中不会生效
  //   additionalData: "@import './src/style/a.scss';",
  // },
  css: {
    preprocessorOptions: {
      scss: {
        // 自动导入全局样式
        // additionalData: "@import '@/styles/base.scss';",
      },
    },
  },
  define: {
    'process.env': JSON.stringify({
      NODE_ENV: '"development"',
      VUE_ENV: '"client"',
      PROXY: PROXY,
    }),
    'process.server': false,
    '__IS_PROD__': false,
    '__SERVER__': false,
  },
  server: {
    port: PORT,
    cors: true,
    // 是否自动在浏览器打开
    open: false,
    // 是否开启 https
    https: false,
    // 服务端渲染
    ssr: false,
    historyApiFallback: {
      rewrites: [{ from: /^\/$/, to: '/index.html' }],
    },
    proxy: {
      // '/api': 'http://127.0.0.1:10002',
      // 如果是 /api 打头，则访问地址如下
      '/api': {
        target: `${devDomain.target}`,
        // target: 'http://127.0.0.1:10002',
        headers: {
          'origin': `${devDomain.origin}`,
          'referer': `${devDomain.origin}`,
          'sec-fetch-site': 'same-site',
          'sec-fetch-mode': 'cors',
          'sec-fetch-dest': 'empty',
        },
        changeOrigin: true, // 是否跨域
        secure: true, // 是否https接口
        configure,
      },
    },
  },
};

createServer({ ...config }).then((e) => {
  console.log('server', e);
  e.listen(PORT);
});
